package com.example.purplestarcb.shoujizhushou;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class Splash extends Activity {
    private TextView banBen;

    protected static final String TAG="Splash";
    protected static final int ENTER_HOME = 1;
    protected static final int URL_ERROR = 2;
    protected static final int NETWORK_ERROR = 3;
    protected static final int JSON_ERROR = 4;
    protected static final int SHOW_UPDATE_DIALOG=5;
    private String description;
    private String apkurl;
    private String version;
    private TextView tv_update_info;

    private SharedPreferences sp;


    /**
     *
     * 版本信息和下载地址
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        banBen =(TextView)findViewById(R.id.banBen);
        tv_update_info=(TextView)findViewById(R.id.tv_update_info);
        banBen.setText(getversionName());

        sp = getSharedPreferences("config", MODE_PRIVATE);
        boolean update = sp.getBoolean("update", false);
        if(update){
            // 检查升级
            checkUpdate();
        }else{
            //自动升级已经关闭
            handler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    //进入主页面
                    enterHome();

                }
            }, 2000);

        }

    }

    private Handler handler;

    {
        handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                switch (msg.what) {
                    case SHOW_UPDATE_DIALOG:// 显示升级的对话框
                        Log.i(TAG, "显示升级的对话框");
                        DisplayTost("有新版本");
                        showUpdateDialog();
                        break;

                    case URL_ERROR:// URL错误
                        DisplayTost("URL错误");
                        enterHome();
                        break;

                    case NETWORK_ERROR:// 网络异常
                        DisplayTost("网络异常");
                        enterHome();
                        break;

                    case JSON_ERROR:// JSON解析出错

                        enterHome();
                        DisplayTost("JSON解析出错");
                        break;

                    default:
                        break;
                }
            }


        };
    }

    public void DisplayTost(String str) {
        Toast.makeText(this,str,Toast.LENGTH_LONG).show();
    }

    /**
     * 显示升级弹出对话框
     */
    private void showUpdateDialog() {

        final Dialog alertDialog=new AlertDialog.Builder(this).setTitle("提示").setMessage(description).setPositiveButton("立即升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    FinalHttp fh=new FinalHttp();
                    fh.download(apkurl,Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/ShouJiWeiShi"+version+".apk",new AjaxCallBack<File>() {
                        @Override
                        public void onSuccess(File file) {
                            DisplayTost("下载成功");
                            super.onSuccess(file);
                            enterHome();
                            installAPK(file);

                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            t.printStackTrace();
                            DisplayTost("下载失败");
                            enterHome();
                            super.onFailure(t, errorNo, strMsg);
                        }

                        @Override
                        public void onLoading(long count, long current) {
                            super.onLoading(count, current);
                            int progress=(int)(current*100/count);
                            tv_update_info.setText(progress+"%");
                        }
                    });
                }

            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                enterHome();
                DisplayTost("取消成功");

            }
        }).create();
        alertDialog.show();
        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                enterHome();
                alertDialog.dismiss();

            }
        });

    }
    /**
     * 安装应用
     */

    private void installAPK(File t){
        Intent intent=new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.fromFile(t),"application/vnd.android.package-archive");
        startActivity(intent);
    }

    /**
     * 进入主页面
     */
    private void enterHome() {
        Intent intent=new Intent(this,ActivityFragmentMain.class);
        startActivity(intent);
        finish();
    }

    /**
     * 检查更新软件
     */
    private void checkUpdate() {
        new Thread(){

            public void run(){
                Message mes=Message.obtain();
                long startTime = System.currentTimeMillis();
                try {
                    //已经得到的信息
                    Message message=Message.obtain();
                    URL url=new URL(getString(R.string.serverurl));
                    //联网
                    HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(4000);
                    int code=conn.getResponseCode();
                    if(code==200){
                        //联网成功
                        InputStream inputStream=conn.getInputStream();
                        //转换流为String
                        String result= StreamTools.readFromStream(inputStream);
                        Log.i(TAG, "联网成功" + result);
                        //Json解析
                        JSONObject obj=new JSONObject(result);
                        version= (String) obj.get("version");
                        description= (String) obj.get("description");
                        apkurl= (String) obj.get("apkurl");
                        //校验是否有新版本

                        if (getversionName().equals(version)){
                            //版本一致进入主页面

                            enterHome();
                        }else{
                            //有新版本弹出版本更新
                            mes.what = SHOW_UPDATE_DIALOG;
                        }
                    }
                } catch (MalformedURLException e) {
                    mes.what = URL_ERROR;
                    e.printStackTrace();
                } catch (IOException e) {
                    mes.what = NETWORK_ERROR;
                    e.printStackTrace();
                } catch (JSONException e) {
                    mes.what = JSON_ERROR;
                    e.printStackTrace();
                }finally {

                    long endTime = System.currentTimeMillis();
                    // 我们花了多少时间
                    long dTime = endTime - startTime;
                    // 2000
                    if (dTime < 2000) {
                        try {
                            Thread.sleep(2000 - dTime);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    handler.sendMessage(mes);
                }

            }
        }.start();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_splash, menu);
        return true;
    }

    private String getversionName(){
        PackageManager pm=getPackageManager();

        try {
            PackageInfo info=pm.getPackageInfo(getPackageName(),0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
